package com.qf.utils;

import com.qf.bean.Employee;
import com.qf.bean.Menu;
import com.qf.bean.Role;
import com.qf.dao.EmployeeDao;
import com.qf.dao.MenuMapper;
import com.qf.dao.RoleMapper;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 26/11/2019
 * Echo
 * qmxc
 * Alibaba
 */
public class MyForm extends FormAuthenticationFilter {
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private MenuMapper menuMapper;
    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject,
                                     ServletRequest request, ServletResponse response) throws Exception {
        Employee employee = (Employee)subject.getPrincipal();
        Role role = roleMapper.findRoleId(employee.getRoleid());
        List<Menu> menus = menuMapper.findByRoleId(role.getRoleid());
        ArrayList firstMenu= new ArrayList();//保存一级菜单
        for (Menu menu : menus) {
            if(menu.getUpmenuid()==0){ //一级菜单
                ArrayList secondList= new ArrayList();//保存二级菜单
                for (Menu second : menus) {
                    if(menu.getMenuid()==second.getUpmenuid()){//如果一级菜单的id(menuid)==二级菜单的父id(upmenuid)
                        secondList.add(second);
                    }
                }
                //将二级菜单的集合封装到一级菜单中
                menu.setSecondList(secondList);
                //将一级菜单在添加到集合中
                firstMenu.add(menu);
            }
        }
        role.setMenuList(firstMenu);
        employee.setRole(role);
        HttpServletRequest req=(HttpServletRequest) request;
        HttpServletResponse res=(HttpServletResponse)response;
        req.getSession().setAttribute("user",employee);
        res.sendRedirect("/index.jsp");
        return false;
    }
}
